import { LOGIN_URL, PUBLICPATH } from "@/config/config";
import router from "@/routers/index";
import { AuthStore } from "@/stores/modules/auth";
import { PublicStore } from "@/stores/modules/public";
import { deepClone, isType } from "@/utils/util";
import { ElNotification } from "element-plus";
import { notFoundRouter } from "./staticRouter";
import { GlobalStore } from "@/stores";
import { screenRouter } from "@/routers/modules/common/screen";
// 引入 views 文件夹下所有 vue 文件
const modules = import.meta.glob("@/views/**/*.vue");
const modulesTsx = import.meta.glob("@/views/**/*.tsx");

/**
 * 初始化动态路由
 */
export const initDynamicRouter = async () => {
	const globalStore = GlobalStore();
	const authStore = AuthStore();
	const publicStore = PublicStore();
	try {
		// 1.获取菜单列表 && 按钮权限（可合并到一个接口获取，根据后端不同可自行改造）
		await authStore.getAuthMenuList();

		// 2.判断当前用户有没有菜单权限
		if (!authStore.authMenuListGet.length) {
			ElNotification({
				title: "无权限访问",
				message: "当前账号无任何菜单权限，请联系系统管理员！",
				type: "warning",
				duration: 3000
			});
			publicStore.setToken("");
			const param = {} as any;
			if (router.currentRoute.value.fullPath != "/") {
				param.redirect = encodeURIComponent(router.currentRoute.value.fullPath);
			}
			router.replace({ path: LOGIN_URL, query: param });
			// router.replace(LOGIN_URL);
			return Promise.reject("No permission");
		}
		// 3.添加动态路由
		authStore.flatMenuListGet.forEach((item: any) => {
			item.children && delete item.children;
			if (item.component && isType(item.component) == "string") {
				if (!item.component.startsWith("/")) {
					item.component = "/" + item.component;
				}
				if (globalStore.setting.home && item.path == "/iot/home") {
					let token = "";
					if (RegExp(/\?.+=.*/).test(globalStore.setting.home)) {
						token = `&token=${publicStore.token}`;
					} else {
						token = `?token=${publicStore.token}`;
					}
					if (globalStore.setting.home.startsWith("http")) {
						item.component = () => import("@/views/dashboard/other/index");

						item.meta.url = globalStore.setting.home + token;
					} else {
						let arr = screenRouter.filter((screenItem: any) => {
							return globalStore.setting.home == screenItem.path;
						});
						if (arr.length && arr[0].meta.url) {
							item.meta.url = arr[0].meta.url + token;
						}
						item.component = arr.length ? arr[0].component : "";
					}
				} else {
					item.component = modulesTsx["/src/views" + item.component + ".tsx"] || modules["/src/views" + item.component + ".vue"];
				}
			}
			if (!item.component || !item.path) {
				// console.warn("page component or path is null.", item);
				return;
			}
			if (item.path && isType(item.path) == "string") {
				if (!item.path.startsWith("/")) {
					item.path = "/" + item.path;
				}
			}

			if (item.meta.isFull) {
				router.addRoute(item);
			} else {
				const pr = deepClone(item);
				pr.path = "/" + PUBLICPATH + pr.path;
				pr.name = pr.name + PUBLICPATH;
				router.addRoute("layoutPublic", pr);
				router.addRoute("layout", item);
			}
		});

		// 4.最后添加 notFoundRouter
		router.addRoute(notFoundRouter);
	} catch (error) {
		// 💢 当按钮 || 菜单请求出错时，重定向到登陆页
		publicStore.setToken("");
		// router.replace(LOGIN_URL);
		const param = {} as any;
		if (router.currentRoute.value.fullPath != "/") {
			param.redirect = encodeURIComponent(router.currentRoute.value.fullPath);
		}
		router.replace({ path: LOGIN_URL, query: param });
		return Promise.reject(error);
	}
};
